<template>
  <div :class="{ show: show }" class="header-search">
    <svg-icon class-name="search-icon" icon-class="search" @click.stop="onClick" />
    <el-select
      ref="headerSearchSelectRef"
      v-model="search"
      :remote-method="querySearch"
      filterable
      default-first-option
      remote
      placeholder="Search"
      class="header-search-select"
      @change="onChange"
    >
      <el-option
        v-for="option in options"
        :key="option.item.path"
        :value="option.item"
        :label="option.item.title.join(' > ')"
      />
    </el-select>
  </div>
</template>

<script setup lang="ts">
// fuse is a lightweight fuzzy-search module
// make search results more in line with expectations
import { ref, watch, computed, nextTick, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import Fuse from 'fuse.js'
import path from 'path-browserify'
import { isHttp } from '@/utils/validate'

// 定义路由项类型
interface RouteItem {
  path: string
  meta?: {
    title: string
  }
  hidden?: boolean
  redirect?: string
  children?: RouteItem[]
  query?: string
}

// 搜索池项类型
interface SearchPoolItem {
  path: string
  title: string[]
  query?: string
}

// Fuse搜索结果类型
interface FuseResult {
  item: SearchPoolItem
  refIndex: number
}

// 定义组件名称
defineOptions({
  name: 'HeaderSearch',
})

// 响应式数据
const search = ref('')
const options = ref<FuseResult[]>([])
const searchPool = ref<SearchPoolItem[]>([])
const show = ref(false)
const fuse = ref<any>(undefined)

// 获取store和router实例
const store = useStore()
const router = useRouter()

// 获取路由
const routes = computed(() => {
  return store.getters.defaultRoutes as RouteItem[]
})

// 模板引用
const headerSearchSelectRef = ref<any>(null)

// 监听routes变化
watch(routes, () => {
  searchPool.value = generateRoutes(routes.value)
})

// 监听searchPool变化
watch(searchPool, (list) => {
  initFuse(list)
})

// 监听show变化
watch(show, (value) => {
  if (value) {
    document.body.addEventListener('click', close)
  } else {
    document.body.removeEventListener('click', close)
  }
})

// 组件挂载时初始化搜索池
onMounted(() => {
  searchPool.value = generateRoutes(routes.value)
})

// 点击事件处理
const onClick = () => {
  show.value = !show.value
  if (show.value) {
    headerSearchSelectRef.value?.focus()
  }
}

// 关闭搜索
const close = () => {
  headerSearchSelectRef.value?.blur()
  options.value = []
  show.value = false
}

// 选择项变化处理
const onChange = (val: SearchPoolItem) => {
  const path = val.path
  const query = val.query
  if (isHttp(val.path)) {
    // http(s):// 路径新窗口打开
    const pindex = path.indexOf('http')
    window.open(path.substr(pindex, path.length), '_blank')
  } else {
    if (query) {
      router.push({ path: path, query: JSON.parse(query) })
    } else {
      router.push(path)
    }
  }
  search.value = ''
  options.value = []
  nextTick(() => {
    show.value = false
  })
}

// 初始化Fuse
const initFuse = (list: SearchPoolItem[]) => {
  fuse.value = new Fuse(list, {
    shouldSort: true,
    threshold: 0.4,
    location: 0,
    distance: 100,
    minMatchCharLength: 1,
    keys: [
      {
        name: 'title',
        weight: 0.7,
      },
      {
        name: 'path',
        weight: 0.3,
      },
    ],
  })
}

// 生成路由
const generateRoutes = (
  routes: RouteItem[],
  basePath = '/',
  prefixTitle: string[] = [],
): SearchPoolItem[] => {
  let res: SearchPoolItem[] = []

  for (const router of routes) {
    // skip hidden router
    if (router.hidden) {
      continue
    }

    const data: SearchPoolItem = {
      path: !isHttp(router.path) ? path.resolve(basePath, router.path) : router.path,
      title: [...prefixTitle],
    }

    if (router.meta && router.meta.title) {
      data.title = [...data.title, router.meta.title]

      if (router.redirect !== 'noRedirect') {
        // only push the routes with title
        // special case: need to exclude parent router without redirect
        res.push(data)
      }
    }

    if (router.query) {
      data.query = router.query
    }

    // recursive child routes
    if (router.children) {
      const tempRoutes = generateRoutes(router.children, data.path, data.title)
      if (tempRoutes.length >= 1) {
        res = [...res, ...tempRoutes]
      }
    }
  }
  return res
}

// 查询搜索
const querySearch = (query: string) => {
  if (query !== '') {
    options.value = fuse.value.search(query)
  } else {
    options.value = []
  }
}
</script>

<style lang="scss" scoped>
.header-search {
  font-size: 0 !important;

  .search-icon {
    cursor: pointer;
    font-size: 18px;
    vertical-align: middle;
  }

  .header-search-select {
    font-size: 18px;
    transition: width 0.2s;
    width: 0;
    overflow: hidden;
    background: transparent;
    border-radius: 0;
    display: inline-block;
    vertical-align: middle;

    :deep(.el-input__inner) {
      border-radius: 0;
      border: 0;
      padding-left: 0;
      padding-right: 0;
      box-shadow: none !important;
      border-bottom: 1px solid #d9d9d9;
      vertical-align: middle;
    }
  }

  &.show {
    .header-search-select {
      width: 210px;
      margin-left: 10px;
    }
  }
}
</style>
